import React, { useState } from 'react';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import FormRender, { useForm } from 'form-render';
// 搜索 表头
import columnsData, { columnsDataType, usrColumns, DataType } from './data';
// 模拟的数据
import tableData from '../../mock/tableData';
import { message, Modal, Popconfirm, Col, Table, Tag } from 'antd';
import {
  getAllTask,
  delegateTask,
  completeTask,
  resolveTask,
  completeTaskWithForm,
  submitTaskFormData,
} from '../../services/processTask';
import { getProcessDefinitionTaskFormData } from '../../services/processFormRepository';
import SearchTree from '../../components/SearchTree';
import { getOrgTree, getUser } from '../../services/upmsServices';
import { ModelView } from 'bsin-workflow-ui';
import { flowableToFormEngine } from '../../utils/formSchemaTransform';
import {
  getCandidateTasksByUser,
  claimCandidateTask,
} from '../../services/TaskClaim';

const TodoClaimTask = () => {
  // table 绑定
  const tableRef = React.useRef<ActionType>();
  const [handleModel, setHandleModel] = useState(false);
  const [handleModelView, setHandleModelView] = useState(false);
  const [formSchema, setFormSchema] = useState({});
  const [taskId, setTaskId] = useState('');
  const [processInstanceId, setProcessInstanceId] = useState('');
  const [processDefinitionId, setProcessDefinitionId] = useState('');

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;

  // 办理
  const transact = async (record: any, handle: any) => {
    console.log(record);
    setTaskId(record.id);
    // 查询判断是否有表单需要提交
    let res = await getProcessDefinitionTaskFormData({
      taskId: record.id,
    });
    if (!res) {
      return message.error('获取处理表单信息失败');
    }
    if (res.data == '') {
      // 没有则直接提交
      // 完成任务
      if (handle == 'resolve') {
        let resolveTaskRes = await resolveTask({
          taskId: record.id,
        });
        tableRef.current?.reload();
        if (resolveTaskRes.code == '000000') {
          return message.success('处理完成');
        }
        return message.error('处理失败');
      } else {
        let completeTaskRes = await completeTask({
          taskId: record.id,
        });
        tableRef.current?.reload();
        if (completeTaskRes.code == '000000') {
          return message.success('处理完成');
        }
        return message.error('处理失败');
      }
    } else if (res.data != '') {
      // 有表单数据
      // 有表单则渲染表单
      console.log('通过');
      let obj = flowableToFormEngine(res.data);
      console.log(JSON.stringify(obj));
      setFormSchema(obj);
      setHandleModel(true);
    }
  };

  // 操作 确认
  const confirm = async (taskId: string) => {
    let res = await claimCandidateTask({ taskId });
    console.log(res);
    if (res.code !== '000000') {
      return message.error('领取失败');
    }
    message.success('领取成功');
    tableRef.current?.reload();
  };

  // 操作 取消
  const onCancel = () => {};

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <Popconfirm
          title={`是否领取？`}
          okText="是"
          cancelText="否"
          onConfirm={() => confirm(record.id)}
          onCancel={onCancel}
        >
          <a>领取</a>
        </Popconfirm>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <a
          onClick={() => {
            setHandleModelView(true);
            setProcessInstanceId(record.processInstanceId);
            setProcessDefinitionId(record.processDefinitionId);
          }}
        >
          流程预览
        </a>
      </li>
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  const form = useForm();

  // 发起表单提交确认
  const handleFormOk = async () => {
    console.log(form.getValues());
    console.log(form.formData);
    let res = await submitTaskFormData({
      variables: form.formData,
      taskId,
    });
    setHandleModel(false);
    tableRef.current?.reload();
    if (res.code != '000000') {
      return message.error('处理失败');
    }
    message.success('处理成功');
  };

  // 发起表单提交取消
  const handleFormCancel = () => {
    setHandleModel(false);
  };

  const onFinish = (formData: any, errors: any) => {
    console.log('formData:', formData, 'errors', errors);
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle="流程任务"
        scroll={{ x: 1000 }}
        actionRef={tableRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={async (params) => {
          let res = await getCandidateTasksByUser({
            ...params,
            pageNum: params.current,
          });
          console.log(res);
          if (res.code !== '000000') {
            message.error('获取流程任务表格信息失败');
          }
          const result = {
            data: res.data,
            total: res.pagination?.totalSize,
          };
          return result;
        }}
        // defaultData={tableData}
        rowKey="id"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'processTaskTable',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
      />
      <Modal
        title="办理"
        open={handleModel}
        onOk={handleFormOk}
        onCancel={handleFormCancel}
      >
        <div style={{ margin: '0 20px 0 0' }}>
          <FormRender form={form} schema={formSchema} onFinish={onFinish} />
        </div>
      </Modal>
      <Modal
        title="流程预览"
        open={handleModelView}
        onCancel={() => setHandleModelView(false)}
        onOk={() => setHandleModelView(false)}
        destroyOnClose
        width={1000}
      >
        <ModelView
          processInstanceId={processInstanceId}
          processDefinitionId={processDefinitionId}
        />
      </Modal>
    </div>
  );
};

export default TodoClaimTask;
